package com.moriarty.socketim.core;

import android.util.Log;

import com.moriarty.socketim.entity.QQMessage;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;

/**
 * Created by Moriarty on 16/11/16.
 */

public class QQConnection extends Thread {

    private String ip;
    private int port;
    private Socket mSocket;
    private DataInputStream dataInputStream;
    private DataOutputStream dataOutputStream;

    private boolean isRunning = false;//线程是否开启

    public QQConnection(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }

    //创建连接
    public void connect() {
        try {
            mSocket = new Socket(ip, port);
            dataInputStream = new DataInputStream(mSocket.getInputStream());
            dataOutputStream = new DataOutputStream(mSocket.getOutputStream());
            isRunning = true;
            start();//开始运行run方法里面的内容(等待服务器传回消息)
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //断开链接
    public void disconnect() {

        try {
            mSocket.close();
            dataInputStream.close();
            dataOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //发送消息
    public void sendMessage(QQMessage msg) {
        try {
            if (dataOutputStream != null) {
                dataOutputStream.writeUTF(msg.toXml());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //接收消息


    private ArrayList<OnMessageListener> list_msgListener = new ArrayList<OnMessageListener>();

    public void addOnMessageListener(OnMessageListener listener) {
        list_msgListener.add(listener);
    }

    public void removeOnMessageListener(OnMessageListener listener) {
        list_msgListener.remove(listener);
    }

    @Override
    public void run() {
//        super.run();
        while (isRunning) {
            try {
                String msg_str = dataInputStream.readUTF();
                QQMessage qqMessage = new QQMessage();
                QQMessage qqMsg = (QQMessage) qqMessage.fromXml(msg_str);

                for (OnMessageListener l : list_msgListener) {
                    l.onGetMessage(qqMsg);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
